<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


/**
 * 打印函数
 * @param $arr
 */
function p($arr)
{
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}

/**
 * md6加密
 * @param $str
 * @return bool|string
 */
function md6($str)
{
    if (!is_string($str)) {
        return false;
    }
    return md5(md5(sha1($str, true), true));
}


/**
 * 日志记录
 * @param string $title
 * @param string $info
 */
function new_log($title = '', $info = '')
{
    if ($info == '') {
        $info = $title;
        $title = '';
    }
    $dir_date = LOG_PATH . '/' . date('Ym') . '/' . date('d');
    mkDirs($dir_date);
    $logfile = $dir_date . '/log.log';
    error_log("\r\n" . date('Y-m-d H:i:s') . $title . ' : ' . print_r($info, true), 3, $logfile);
}


function mkDirs($dir)
{
    if (!is_dir($dir)) {
        if (!mkDirs(dirname($dir))) {
            return false;
        }
        if (!mkdir($dir, 0777)) {
            return false;
        }
    }
    return true;
}

/**
 * 生成四位随机数
 * @return int
 */
function random()
{
    return strval(rand(1000,9999));
}


/**
 * 获取客户端IP
 * PS: 无法透视VNP 待优化
 * @param bool|false $type 不传默认false 只取IP 传TRUE顺带取地区
 * @return array|string
 */
function get_ip($type = false)
{
    $realip = '';
    if (isset($_SERVER)){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }

    if($realip == '::1'){
        $realip = '127.0.0.1';
    }

    $arr = $type == false ? $realip : ['ip'=>$realip,'area'=> $realip == '127.0.0.1' ? '本地' : ipToArea($realip)];
    return $arr;
}

/**
 * IP转地址
 * @param $queryIP
 * @return string
 */
function ipToArea($queryIP){
    $url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$queryIP;
    $ch = curl_init($url);
    //curl_setopt($ch,CURLOPT_ENCODING ,'utf8');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
    $location = curl_exec($ch);
    $location = json_decode($location);
    curl_close($ch);
    $loc = "";
    if($location){
        if ( 0 == $location->code) {
            if(empty($location->data->city)){
                $loc = $location->data->country;
            }else{
                $loc = $location->data->region.$location->data->city;
            }
        }
    }
    return $loc;
}

/**
 * 是否手机端
 * @return bool
 */
function isMobile()
{
    //如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        }
    }
    return false;
}


//数组转对象
function arrayToObject($e){
    if( gettype($e)!='array' ){
        return false;
    }
    foreach($e as $k=>$v){
        if( gettype($v)=='array' || getType($v)=='object' )
            $e[$k]=(object)arrayToObject($v);
    }
    return (object)$e;
}

//对象转数组
function objectToArray($e){
    $e=(array)$e;
    foreach($e as $k=>$v){
        if( gettype($v)=='resource' ){
            return false;
        }
        if( gettype($v)=='object' || gettype($v)=='array' )
            $e[$k]=(array)objectToArray($v);
    }
    return $e;
}


/**
 * 自动转换字节单位
 * @param $size
 * @return string
 */
function getSize($size) {
    if($size >= 1073741824) {
        $size = round($size / 1073741824 * 100) / 100 . ' gb';
    } elseif($size >= 1048576) {
        $size = round($size / 1048576 * 100) / 100 . ' mb';
    } elseif($size >= 1024) {
        $size = round($size / 1024 * 100) / 100 . ' kb';
    } else {
        $size = $size . ' bytes';
    }
    return $size;
}



/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <static7@qq.com>
 */
function send_mail($tomail, $title = '', $body = '', $attachment = null) {
    $mail = new \PHPMailer();           //实例化PHPMailer对象
    $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能

    $email = \think\Config::get('email');

    $mail->Host = $email['host']; // SMTP 服务器
    $mail->Username = $email['user'];    // SMTP服务器用户名
    $mail->Password = $email['pass'];     // SMTP服务器密码
    $mail->SetFrom($email['user'],$email['name']);//发件人地址及昵称

    $mail->Subject = $title;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}


